<template>
  <a-modal :title="title" :after-close="reset" @ok="submit">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ style: { width: '80px' } }"
    >
      <a-form-item name="roleName" label="角色名称">
        <a-input v-model:value="form.roleName" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="status" label="状态">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="true"> 启用 </a-radio>
          <a-radio :value="false"> 禁用 </a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item name="menuIdList" label="功能权限">
        <a-tree
          v-if="menuData.length"
          v-model:checkedKeys="form.rules"
          checkable
          :tree-data="menuData"
          default-expand-all
          :height="300"
          :field-names="{
            title: 'name',
            key: 'id',
            children: 'children',
          }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { saveRole, getRoleById } from '@/api/role';
import { Role, type IRole } from '@/types/role';
import { validReg } from '@/utils/validate';
import { getMenus } from '../menu/api';
import type { IMenu } from '../menu/entity';
import { TreeSelect } from 'ant-design-vue'
import type { DataNode } from 'ant-design-vue/es/tree';

const props = withDefaults(defineProps<{
  data: Partial<IRole>
}>(),{
})
const title = computed(() => props.data.id ? '编辑' : '新增')
const { formRef, submit, close } = useDialog({ validCallback: save, id: 'id' })

let form = $ref(new Role())
watchEffect(() => {
  if (props.data.id) {
    getRoleById(props.data.id).then(role => {
      form.setProps(role)
      form.rules =[]
       getTreeId(role.menuList)
    })
  }
})
function getTreeId(datas: any) {
  for (var i in datas) {
    if (datas[i].checked) form.rules.push(datas[i].id)
    if (datas[i].childList) {
      getTreeId(datas[i].childList);
    }
  }
}
const rules = {
  roleName: [validReg('required', '请输入角色名称')],
  deptId: [validReg('required', '请选择所属部门', 'change')]
}

onMounted(() => {

  getMenuTree()
})
const emit = defineEmits(['change'])
function save() {
  const data = { ...form,rules: form.rules.join() }
  saveRole(data).then(() => {
    AntMessage.success('保存成功')
    close()
    emit('change')
  })
}



let menuData = $ref<IMenu[]>([])
function getMenuTree() {
  getMenus().then((res) => {
    menuData = res.list
  })
}

function reset() {
  form = new Role()
}
</script>

<style lang="less"></style>
